package org.langqiao.io.gzip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipReadAndWrite {
	public static void main(String[] args){
		readFileAndWriteGzip();
		
		readGzipAndWriteFile();
	}
	
	//读文件，写入Gzip文件中
	public static void readFileAndWriteGzip(){
		FileInputStream fin = null;
		FileOutputStream fout = null;
		GZIPOutputStream gzout = null;
		byte[] buff = null;
		try {
			fin = new FileInputStream(new File("D:/test/2.txt"));
			fout = new FileOutputStream(new File("D:/test/2.zip"));
			gzout = new GZIPOutputStream(fout);
			int num = 0;
			buff = new byte[1024];
			while((num = fin.read(buff))!=-1){
				gzout.write(buff, 0, num);
			}
		} catch (Exception e) {
			
		}
		finally{
			try {
				gzout.flush();
				gzout.finish();
				gzout.close();
				fin.close();
				fout.close();		
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}

	//读Gzip文件，写入到.txt文件中
	public static void readGzipAndWriteFile(){
		
		FileInputStream fin = null;
		FileOutputStream fout = null;
		GZIPInputStream gzin = null;
		byte[] buff = null;
		try {
			fin = new FileInputStream(new File("D:/test/2.zip"));
			gzin = new GZIPInputStream(fin);
			fout = new FileOutputStream(new File("D:/test/3.txt"));			
			int num = 0;
			buff = new byte[1024];
			while((num = gzin.read(buff))!=-1){
				fout.write(buff, 0, num);
			}
		} catch (Exception e) {
			
		}
		finally{
			try {
				fin.close();
				fout.close();
				gzin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
}
